//
//  imprint
//
//  Created by 小柠檬🍋 on 2025/1/16.
//

import Foundation
import LeanCloud

//制作音色
class MakeVoiceViewModel : BaseViewModel {
    @Published var items = [AiVoiceCrowdBean]()
    @Published var status = ""
    
    func getData(_ isRefresh: Bool = false, status : Int) {
        requestList(isRefresh: isRefresh) {
            let query = LCQuery(className: "AiVoiceCrowd")
            query.whereKey("status", .equalTo(status))
            query.whereKey("hide", .notEqualTo(true))
            query.whereKey("count", .descending) //count 降序
            query.limit = self.pageSize
            query.skip = self.pageNo * self.pageSize
            let list = try await LeancloudManager.instance.getList(query: query, modeType: AiVoiceCrowdBean.self)
            try check(!isRefresh || !list.isEmpty, "暂无音色")
            return list
        } suc: {
            self.status = ""
            self.items.append(contentsOf: $0)
        } fail: {
            self.status = $0.message
        }
    }
    
    func doCreate(media: MediaItem?,name:String?, price: Double?, deduct : Bool = false) {
        if media == nil {
            return
        }
        request {
            try check(userManager.isLogin(), "请先登陆")
            let key = "voice/\(try await getNetTime())"
            switch media!.type {
            case .localVideo(let url):
                let qiniuReturn = try await retry(maxRetries: 5, retryDelayMillis: 500) {
                    try await QiniuManager.shared.upload(url : url, key: key ,modeType: QiniuResult.self)
                }
                //更新AiVoiceCrowdBean
                let crowdBean = try await retry(maxRetries: 5, retryDelayMillis: 500) {
                    let crowdBean = AiVoiceCrowdBean()
                    crowdBean.name = name
                    crowdBean.fileId = qiniuReturn.getUrl()
                    crowdBean.price = price ?? 0
                    crowdBean.buyPrice = 5.0
                    crowdBean.status = 0
                    let objectId = try await LeancloudManager.instance.saveToId(todo: crowdBean)
                    crowdBean.objectId = objectId
                    return crowdBean
                }
                //更新AiVoiceCrowdBean
                try await retry(maxRetries: 5, retryDelayMillis: 500) {
                    let crowdDataBean = AiVoiceCrowdDataBean()
                    crowdDataBean.crowdId = crowdBean.objectId
                    crowdDataBean.userId = userManager.getUserId()
                    crowdDataBean.price = price
                    try await LeancloudManager.instance.save(todo: crowdDataBean)
                }
                //更新AiVoiceBean
                try await retry(maxRetries: 5, retryDelayMillis: 500) {
                    let voiceBean = AiVoiceBean()
                    voiceBean.name =  crowdBean.name
                    voiceBean.userId = userManager.getUserId()
                    voiceBean.crowdId = crowdBean.objectId
                    try await LeancloudManager.instance.save(todo: voiceBean)
                }
                //扣除次数
                if (deduct) {
                    try await retry(maxRetries: 5, retryDelayMillis: 500) {
                        var aiVoiceCreate = userManager.getExtraConfig().aiVoiceCreate ?? 0
                        aiVoiceCreate -= 1
                        userManager.getExtraConfig().aiVoiceCreate = aiVoiceCreate
                        try await userManager.requestAsync(user: userManager.user)
                    }
                }
            case .networkImage(_, _, _):
                break
            case .localImage(_):
                break
            case .localImagePath(_):
                break            }
            
            return true
        } suc: { _ in
            showTipsDialog(text: "发起成功")
            NotificationCenter.default.post(name: .buyVoice, object: true)
            self.items.removeAll()
            self.resetPage()
            self.getData(status: 0)
        } fail: {it in
            showTipsDialog(text: it.message) {}
        }
        
    }
    
}
